<template>
	<div class="login">
		<div class="login-container">
			<div class="login-header">
				<div class="login-header-title">账号登录</div>
				<p class="login-header-info">晨光 - 严选商城欢迎您</p>
			</div>
			<Input
					icon="icon-mobile"
					type="text"
					placeholder="手机号码"
					maxLength="11"
					:required="true"
					v-model.number="form.mobile"
					:rules="rules.mobile"
			/>
			<Input
					type="password"
					placeholder="密码"
					:required="true"
					v-model="form.pwd"
					:rules="rules.pwd"
			/>
			<div class="login-btn">
				<button @click="submit">登录</button>
			</div>
			<div class="login-forget">
				<router-link to="/">忘记密码</router-link>
			</div>
			<div class="login-register">
				<router-link to="/register">还没有注册？ 立即注册</router-link>
			</div>
		</div>
	</div>
</template>

<script>
	import User from '@/services/user';
	import Input from '#/Public/Input';
	import {mapActions} from 'vuex';
	import {PHONE, PWD} from '@/utils/RegExp';

	const _user = new User();
	export default {
		name: "Login",
		data() {
			return {
				form: {
					mobile: '',
					pwd: ''
				},
				rules: {
					mobile(value) {
						return PHONE.test(value);
					},
					pwd(value) {
						return PWD.test(value);
					}
				}
			}
		},
		methods: {
			...mapActions(['getUserDetail']),
			validator() {
				let flag = true;
				for (let i in this.form) {
					if (!this.rules[i](this.form[i])) {
						flag = false;
					}
				}
				return flag;
			},
			submit() {
				if (this.validator()) {
					_user.userLogin(this.form).then(res => {
						this.getUserDetail(res.data.token);
						this.$message({
							type: 'success',
							message: '登录成功！'
						});
						let path = this.$route.query.redirect || '/';
						this.$router.push(path);
					})
				}
			}
		},
		components: {
			Input
		}
	}
</script>
